package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @author SunSun
 * @date 2021/10/31
 */
@DubboService
public class UserLikeApiImpl implements UserLikeApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public boolean saveOrUpdate(Long userId, Long likeUserId, boolean b) {
        try {
            Query query=Query.query(Criteria.where("userId").is(userId)
                    .and("likeUserId").is(likeUserId));
            UserLike one = mongoTemplate.findOne(query, UserLike.class);
            if(one==null){
                UserLike userLike=new UserLike();
                userLike.setUserId(userId);
                userLike.setLikeUserId(likeUserId);
                userLike.setCreated(System.currentTimeMillis());
                userLike.setUpdated(System.currentTimeMillis());
                userLike.setIsLike(b);
                mongoTemplate.save(userLike);
            }else{
                Update update=Update.update("isLike",b)
                        .set("updated",System.currentTimeMillis());
                mongoTemplate.updateFirst(query,update,UserLike.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Integer loveCount(Long userId) {
        Query query=Query.query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, UserLike.class);
        return Integer.parseInt(String.valueOf(count));
    }

    @Override
    public Integer fanCount(Long userId) {
        Query query=Query.query(Criteria.where("likeUserId").is(userId));
        long count = mongoTemplate.count(query, UserLike.class);
        return Integer.parseInt(String.valueOf(count));
    }

    @Override
    public Integer eachLoveCount(Long userId) {
        Integer eachLoveCount=0;
        Query query=Query.query(Criteria.where("userId").is(userId));
        List<UserLike> likeList = mongoTemplate.find(query, UserLike.class);
        for (UserLike userLike : likeList) {
            Query query1=Query.query(Criteria.where("userId").is(userLike.getLikeUserId())
                    .and("likeUserId").is(userId));
            boolean exists = mongoTemplate.exists(query1, UserLike.class);
            if(exists){
                eachLoveCount++;
            }
        }
        return eachLoveCount;
    }
}
